<template>
  <!-- 车辆台账 -->
  <base-breadcrumb :title="$route.meta.title">
    <!-- 搜索 -->
    <searchData ref="searchData" :searchData="searchArr" @search="search"></searchData>
    <!-- 表格 -->
    <a-card :bordered="false">
      <!-- <title-name :title="$route.meta.title"></title-name> -->
      <div class="mb12">
        <!-- v-if="post.code === 'PDAZR' || post.code === 'BCACLGL' || post.code === 'COACLGL'" -->

        <!-- 导出 -->
        <!-- <excel
          class="ml12"
          ref="exportAll"
          :fileName="fileName"
          is-click-generate="false"
        >
          <a-button type="primary" icon="download" :loading="loading" slot="excelBtn" @click="exportAll">导出</a-button>
        </excel> -->
      </div>
      <!-- 表格 -->
      <list-table ref="table" row-key="id" :columns="columns" :request="loadData" :alert="true" show-size-changer
        show-quick-jumper :export-config="{ use: true, select: `${fileName}`, all: `${fileName}` }"
        :statisticsConfig="{ use: true, temp: statisticsTemp }">
        <a-button slot="prefix" icon="plus" type="primary" @click="handleManage(2)">新增车辆</a-button>
        <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
        <template slot="actions" slot-scope="text, record">
          <!-- (post.code === 'PDAZR' || post.code === 'BCACLGL' || post.code === 'COACLGL') -->
          <MoreButton>
            <a @click="handleManage(0, record)">查看</a>
            <template v-if="record.unitId === post.id">
              <a-divider type="vertical"></a-divider>
              <a @click="handleManage(1, record)">编辑</a>
            </template>
            <a-divider type="vertical" v-btnPermission="'oa_022_cyj_05'"></a-divider>
            <a @click="vehicleHandOver(record)" v-btnPermission="'oa_022_cyj_05'">车辆移交</a>
          </MoreButton>
        </template>
        <!-- 状态 -->
        <template slot="state" slot-scope="text, record">
          <status-display :statusCode="record.state" :statusMap="statusMap"></status-display>
        </template>
      </list-table>
    </a-card>
    <!-- 车辆移交 -->
    <BaseModal title="车辆移交" :visible="visible" :confirm-loading="confirmLoading" width="600px" destroyOnClose
      @cancel="handleCancel">
      <a-form :form="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="当前所属单位">
          <a-input v-model="vehicleHandOverForm.unitName" disabled />
        </a-form-item>
        <a-form-item label="移交单位名称" class="requiredFormItem">
          <a-tree-select v-model="vehicleHandOverForm.transferUnitId" style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :replaceFields="{ children: 'children', title: 'label', key: 'id', value: 'id' }" :tree-data="treeData"
            placeholder="请选择" allowClear v-decorator="[
              'transferUnitId',
              { rules: [{ required: true, message: '请选择移交单位名称' }] }
            ]" @select="changeTransferUnit" treeNodeFilterProp="title" show-search>
          </a-tree-select>
        </a-form-item>
      </a-form>
      <div slot="footer" class="btn_box">
        <a-button type="default" @click="handleCancel">
          取消
        </a-button>
        <a-button type="primary" html-type="submit" @click="handleOk">
          确定
        </a-button>
      </div>
    </BaseModal>
  </base-breadcrumb>
</template>

<script>
// import { STable } from '@/components' // 表格
import { carInfo } from '@/api/office/vehicle/config' // api
import Selector from '@/components/Select/Selector'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject' // 申请单位
import StatusDisplay from '@/components/StatusDisplay'
import OrgTreeSelect from '@/components/OrgTreeSelect'
import BasePage from '@/views/basePage' // 基础配置
import BaseModal from '@/components/BaseModal'
import { getCustOrgTree } from '@/api/subassembly/TreeSelectOrganization'

const searchArr = [
  // 搜索框
  {
    name: '所属单位',
    valueKey: 'searchQuery',
    type: OrgTreeSelect,
    attr: {
      isAutoSelectFirst: true
    }
  },
  // {
  //   name: '所属单位',
  //   valueKey: 'unitId',
  //   type: SelectCompanyAndProject,
  // },
  {
    valueKey: 'carNature',
    name: '车辆性质',
    type: Selector,
    valueName: 'code',
    selectType: '48',
    urlType: 'union',
  },
  {
    name: '车牌号',
    type: 'input',
    value: 'carNumber',
  },
]
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    scopedSlots: { customRender: 'index' }
  },
  {
    title: '所属单位',
    ellipsis: true,
    dataIndex: 'unitName',
  },
  {
    title: '车辆性质',
    ellipsis: true,
    dataIndex: 'carNatureName',
  },
  {
    title: '车牌号',
    ellipsis: true,
    dataIndex: 'carNumber',
  },
  {
    title: '品牌型号',
    ellipsis: true,
    dataIndex: 'brand',
  },
  {
    title: '车辆类型',
    ellipsis: true,
    dataIndex: 'carTypeName',
  },
  {
    title: '限行时间',
    ellipsis: true,
    dataIndex: 'forbid',
  },
  {
    title: '随车司机',
    ellipsis: true,
    dataIndex: 'driverName',
  },
  {
    title: '年审日期',
    ellipsis: true,
    dataIndex: 'auditTime',
  },
  {
    title: '状态',
    dataIndex: 'state',
    scopedSlots: { customRender: 'state' },
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: 220,
    operColumnC: true,//操作列宽度是否自定义
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'actions' },
  },
]
export default {
  name: 'a' + Date.now(),
  extends: new BasePage(),
  components: {
    // STable,
    StatusDisplay,
    BaseModal,
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      loading: false, // 导出loading
      queryParam: {}, // 查询参数
      loadData: (parameter) => {
        // if (!this.init) {
        //   return false
        // }
        this.getSummary()
        const requestParameters = Object.assign({}, parameter, { query: this.queryParam })
        return carInfo.getList(requestParameters).then((res) => {
          return res
        })
      }, // 加载数据方法 必须为 Promise 对象
      statusMap: {
        0: {
          label: '不可用',
          color: '#ff9900',
        },
        1: {
          label: '可用',
          color: '#00A854',
        },
      },
      summary: {}, // 统计
      post: {
        code: '', // 登录人组织code
        orgId: '', // 登录人组织id
      },
      init: false, // 弹窗初始化标识
      fileName: '车辆台账', // 导出文件名
      rowData: {},
      form: this.$form.createForm(this, { name: 'coordinated' }),
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      vehicleHandOverForm: {
        id: null,
        unitId: null,
        unitName: null,//所属单位
        carNumber: null,//车牌号
        transferUnitId: null,//移交单位ID
        transferUnitName: null,//移交单位名称
      },
      treeData: [],
      visible: false,
      confirmLoading: false,
    }
  },
  mounted() {
    // 获取当前岗位
    this.post = this.$currentPost()
    this.$refs.searchData.form.setFieldsValue({
      // unitId: this.post?.id,
      // searchQuery: {
      //   _checked: this.$currentPost()?.id
      // }
    })
    this.init = true
    this.search({
      // unitId: this.post?.id,
      // searchQuery: {
      //   _checked: this.$currentPost()?.id
      // }
    })
    this.getCustOrgTreeData();
  },
  methods: {
    /**
*  移交单位树节点改变
*/
    changeTransferUnit(value, node, extra) {
      this.vehicleHandOverForm.transferUnitId = extra.node.value;
      this.vehicleHandOverForm.transferUnitName = extra.node.title;
    },
    /**
*  获取组织机构树
*/
    async getCustOrgTreeData() {
      let params = {
        baseOrgType: 0,
        types: "1,3",
        orgDeptTagCodeAll: 0
      }
      let res = await getCustOrgTree(params)
      this.treeData = res.data
    },
    /**
 *  操作车辆移交按钮
 */
    vehicleHandOver(row) {
      let { unitName, unitId, id, carNumber } = row;
      this.rowData = row;
      this.vehicleHandOverForm.unitName = unitName;
      this.vehicleHandOverForm.unitId = unitId;
      this.vehicleHandOverForm.id = id;
      this.vehicleHandOverForm.carNumber = carNumber
      this.visible = true;
    },
    /**
*  关闭车辆移交弹窗
*/
    handleCancel() {
      this.rowData = null;
      this.visible = false;
    },
    /**
*  提交
*/
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.$confirm({
            title: '温馨提示',
            content: '请确认是否要移交车辆，移交成功后，需重新设置该车辆的随车司机',
            onOk: () => {
              carInfo.saveCarHandOver(this.vehicleHandOverForm).then((res) => {
                if (res.code === '0') {
                  this.$message.success('移交成功')
                  this.handleCancel();
                  this.$refs.table.refresh(true)
                } else {
                  this.$message.warning(res.msg || '移交失败')
                }
              }).catch((error) => { })
            }
          })
        }
      });
    },
    /**
     * 统计
     */
    getSummary() {
      carInfo.summary(Object.assign({}, this.queryParam)).then((res) => {
        if (res.data) {
          this.summary = res.data
        }
      })
    },
    statisticsTemp() {
      return (
        <span>
          <span>自有车辆数量：<a>{this.summary.selfCarSum || 0}</a></span>
          <span style="margin-left:5px">租赁车辆数量：<a>{this.summary.rentCarSum || 0}</a></span>
        </span>
      )
    },
    /**
     * 导出
     */
    exportAll() {
      this.loading = true
      carInfo
        .getAllList(Object.assign({}, this.$refs.searchData.form.getFieldsValue()))
        .then((res) => {
          this.loading = false
          if (res.data?.length > 0) {
            res.data.forEach((item, index) => {
              item.index = index + 1
              item.state = ['不可用', '可用'][item.state]
              if (item.rentEndTime && item.rentStartTime) {
                item.rentTime = item.rentStartTime + '至' + item.rentEndTime
              }
            })
            const GZ = res.data.filter((item) => item.carNature === 'GZ')
            const ZN = res.data.filter((item) => item.carNature === 'ZN')
            // 导出购置车辆
            if (GZ?.length > 0) {
              this.fileName = this.post.name + '_购置车辆台账'
              this.initColumn(0)
              this.$refs.exportAll.setDataAndGenerate(GZ)
            }
            // 导出租赁车辆
            if (ZN?.length > 0) {
              setTimeout(() => {
                this.fileName = this.post.name + '_租赁车辆台账'
                this.initColumn(1)
                this.$refs.exportAll.setDataAndGenerate(ZN)
              }, 500)
            }
            this.$message.success('导出成功')
          } else {
            this.$message.warning('没有数据可以导出')
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 导出初始化
    initColumn() {
      let columns = [
        {
          title: '车身颜色',
          dataIndex: 'color',
        },
        {
          title: '发动机号',
          dataIndex: 'engineNumber',
        },
        {
          title: '排气量',
          dataIndex: 'gas',
        },
        {
          title: '车架号',
          dataIndex: 'chassisNumber',
        },
        {
          title: '加油卡号',
          dataIndex: 'gasCardNumber',
        },
      ]
      if (arguments[0] === 0) {
        columns = columns.concat([
          {
            title: '购置单位',
            dataIndex: 'buyUnitName',
          },
          {
            title: '购置时间',
            dataIndex: 'buyTime',
          },
          {
            title: '购置总金额（元）',
            dataIndex: 'buyAmount',
          },
          {
            title: '车辆裸车价（元）',
            dataIndex: 'carPrice',
          },
        ])
      } else {
        columns = columns.concat([
          {
            title: '租车单位',
            dataIndex: 'rentUnitName',
          },
          {
            title: '租赁期限',
            dataIndex: 'rentTime',
          },
          {
            title: '租车费用（元/月，不含司机）',
            dataIndex: 'carCost',
          },
          {
            title: '司机费用（元/月）',
            dataIndex: 'driverCost',
          },
        ])
      }
      // 初始化
      this.$refs.exportAll.tableToExcelFile(
        {
          columns: this.columns.concat(columns),
        },
        0
      )
    },
    /**
     * 搜索
     */
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.refresh(true)
    },
    /**
     * 操作栏
     */
    handleManage(type, record) {
      let query = {
        editModel: type,
      }
      if (record && record.id) {
        query.id = record.id
      }
      this.$router.push({
        name: '/vehicle/carTableEdit',
        query,
      })
    },
  },
}
</script>
